
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {PageContainer, ProTable, } from '@ant-design/pro-components';
import {Button, Divider, Popconfirm, Space, Typography} from 'antd';
import {
  endTask,
  getTaskAttackList,
  searchTaskByDescLikeyly, searchTaskByStatus, searchTaskByTaskNameLikeyly, startTask
} from "@/services/ant-design-pro/api";
import message from "antd/es/message";
import {useRef, useState} from "react";
import CreateModal from "@/pages/Admin/TaskAttackMange/components/CreateModal";
import AssignTesterModal from '@/pages/Admin/TaskAttackMange/components/AssignTesterModal'; // 替换成实际的组件路径

import 'antd/dist/antd.css';


/**
 * 开始任务
 * @param selectedRows 选中的任务行数据
 */
const doStartTask = async (selectedRows: API.TaskAttack[]) => {
  if (!selectedRows || selectedRows.length === 0) {
    message.warning('请先选择要开始的任务');
    return;
  }

  const taskId = selectedRows[0].id;  // 假设任务的唯一标识符存储在 id 字段中

  try {
    const result = await startTask(taskId);
    if (result.code === 200 && result.data) {
      message.success('任务已成功开始');
      // 在这里你可能需要更新页面上的任务状态等

    } else {
      message.error(result.description || '操作失败');
    }
  } catch (error) {
    message.error('操作失败，' + error.message);
  }
};

/**
 * 结束任务
 * @param selectedRows 选中的任务行数据
 */
const doEndTask = async (selectedRows: API.TaskAttack[]) => {
  if (!selectedRows || selectedRows.length === 0) {
    message.warning('请先选择要结束的任务');
    return;
  }
  const task = selectedRows[0];
  const taskId = task.id;

  // 在这里增加判断任务状态的逻辑
  if (task.taskstatus === '未开始') {
    message.warning('当前任务未开始');
    return;
  }
  try {
    const result = await endTask(taskId);
    if (result.code === 200 && result.data) {
      message.success('任务已成功结束');
      // 在这里你可能需要更新页面上的任务状态等

    } else {
      message.error(result.description || '操作失败');
    }
  } catch (error) {
    message.error('操作失败，' + error.message);
  }
};

/**
 * 演练任务管理页面
 * @constructor
 */
const AdminUserPage: React.FC<unknown> = () => {

  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [assignTesterModalVisible, setAssignTesterModalVisible] = useState<boolean>(false);
  const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null);

  const actionRef = useRef<ActionType>();
  const handleOpenAssignTesterModal = (taskId: number) => {
    setSelectedTaskId(taskId);
    setAssignTesterModalVisible(true);
  };

  const handleAssignTesterSuccess = () => {
    // 在任务指派成功后的逻辑，比如刷新列表等
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const columns: ProColumns<API.TaskAttack>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '任务名称',
      dataIndex: 'taskname',
      copyable: true
    },
    {
      title: '任务描述',
      dataIndex: 'taskdesc',
      copyable: true
    },
    {
      title: '任务关联的组织机构',
      dataIndex: 'relatedorg',
      copyable: true
    },
    {
      title: '参与的测试人员',
      dataIndex: 'joinedtesters',
      copyable: true
    },    {
      title: '任务状态',
      dataIndex: 'taskstatus',
      copyable: true,
      render: (text) => (
        <span style={{ color: text === '进行中' ? 'green' : 'red' }}>{text}</span>
      ),
    },
    {
      title: '活动开始时间',
      dataIndex: 'starttime',
      copyable: true
    },
    {
      title: '活动结束时间',
      dataIndex: 'endtime',
      copyable: true
    },



    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space split={<Divider type="vertical" />}>
          <Popconfirm
            title="您确定要开始任务么？"
            onConfirm={() => doStartTask([record])}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link disabled={record.taskstatus === '已完成' || record.taskstatus === '进行中'} >开始任务</Typography.Link>
          </Popconfirm>
          <Typography.Link onClick={() => handleOpenAssignTesterModal(record.id)}>任务指派</Typography.Link>
          <Popconfirm
            title="您确定要结束任务么？"
            onConfirm={() => doEndTask([record])}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">结束任务</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },

  ];

  return (
    <PageContainer>
      <ProTable<API.TaskAttack>
        headerTitle="演练任务管理"
        actionRef={actionRef}
        columns={columns}
        // @ts-ignore
        request={async (params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          if (params.taskname) {
            // 如果有 taskname 参数，调用按名称查询接口
            const result = await searchTaskByTaskNameLikeyly(params.taskname);
            return Promise.resolve({
              data: result.data
            });
          }else if(params.taskdesc){
            // 如果有 taskdesc 参数，调用按父类机构查询接口
            const result = await searchTaskByDescLikeyly(params.taskdesc);
            return Promise.resolve({
              data: result.data
            });
          } else if(params.taskstatus){
            // 如果有 taskstatus 参数，调用按父类机构查询接口
            const result = await searchTaskByStatus(params.taskstatus);
            return Promise.resolve({
              data: result.data
            });
          } else {
            // 否则调用查询所有组织机构的接口
            const result = await getTaskAttackList();
            return Promise.resolve({
              data: result.data
            });
          }
        }}
        rowKey="key"
        pagination={{
          showQuickJumper: true,
        }}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        dateFormatter="string"
        toolbar={{
          title: '演练任务列表',
          tooltip: '',
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => setCreateModalVisible(true)}
          >
            添加演练任务
          </Button>,
        ]}
      />
      <CreateModal
        modalVisible={createModalVisible}
        columns={columns}
        onSubmit={() => setCreateModalVisible(false)}
        onCancel={() => setCreateModalVisible(false)}
      />

      <AssignTesterModal
        taskId={selectedTaskId || 0}
        modalVisible={assignTesterModalVisible}
        onCancel={() => setAssignTesterModalVisible(false)}
        onAssignSuccess={handleAssignTesterSuccess}
      />

    </PageContainer>
  );
};
export default AdminUserPage;
